package com.lzs.system.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzs.entity.LoginLog;
import com.lzs.entity.User;
import com.lzs.system.service.DeptService;
import com.lzs.system.service.LoginLogService;
import com.lzs.system.service.RoleService;
import com.lzs.system.service.UserService;
import com.lzs.util.ActivierUser;
import com.lzs.system.vo.LoginVO;
import com.lzs.util.JwtUtils;
import com.lzs.util.R;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author 刘中帅
 * @since 2020-11-24
 */
@RestController
@RequestMapping("/system/user")
@ApiModel(value = "用户管理")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private LoginLogService loginLogService;
    @PostMapping("/login")
    @ApiOperation(value = "登陆功能")
    public R login(@RequestBody LoginVO loginVO,HttpServletRequest request){
        ActivierUser activierUser = userService.selectUserByUserName(loginVO);
        String ip = userService.getIpAddr(request); //获取登录人IP地址
        LoginLog loginLog=new LoginLog();
//        if (activierUser.getStatus()==1||activierUser.getStatus()==2) {
//            return R.error().message("账号或密码错误");
//        }else if (activierUser.getStatus()==3){
//            return R.error().message("账号被冻结");
        if (activierUser==null){
            R r = R.error().message("账号或密码错误");
            // 添加登录失败日志
            loginLog.setLogName("登录失败日志");
            loginLog.setIpAddress(ip);
            loginLog.setCreateTime(new Date());
            loginLog.setSucceed("失败");
            loginLog.setMessage("账号:"+loginVO.getUsername()+"账号或密码错误");
            loginLogService.save(loginLog);
            return r;
        }else {
            // 得到token
            String token = JwtUtils.createJWT(activierUser.getUser().getUserId());
            redisTemplate.opsForValue().set("user::"+activierUser.getUser().getUserId(),
                    JSON.toJSONString(activierUser),1, TimeUnit.DAYS);
            // 把数据返回到前台
            R data = R.ok().message("登录成功").data("token", token).data("activierUser", activierUser);
            // 添加登录成功日志
            loginLog.setLogName("登录成功日志");
            loginLog.setIpAddress(ip);
            loginLog.setUserId(activierUser.getUser().getUserId());
            loginLog.setCreateTime(new Date());
            loginLog.setSucceed("成功");
            loginLogService.save(loginLog);
            return data;
        }
    }
    @PostMapping("/logout")
    @ApiOperation(value = "登出功能")
    public R logout(HttpServletRequest request){
        String ip = userService.getIpAddr(request); //获取登录人IP地址
        LoginLog loginLog=new LoginLog();
        // 得到token信息
        String token = request.getHeader("token");
        // 检验token 是否有效u
        if (!JwtUtils.checkToken(token)==true){
            return R.error();
        }else {
            // 解析token得到用户Id
            Long userId = JwtUtils.getMemberIdByJwtToken(token);
//            System.out.println(userId + "``````````````````");
            //清除redis数据
            redisTemplate.delete("user::" + userId);
            // 添加退出日志
            loginLog.setUserId(userId);
            loginLog.setLogName("退出日志");
            loginLog.setIpAddress(ip);
            loginLog.setCreateTime(new Date());
            loginLog.setSucceed("成功");
            loginLogService.save(loginLog);
            return R.ok();
        }
    }
    @PostMapping("/selectAllUserPage/{page}/{limit}")
    @ApiOperation(value = "用户分页查询")
    public Page<User> selectDeptAll(@PathVariable Integer page, @PathVariable Integer limit, @RequestBody User user){
        Page<User> userPage = userService.selectAllUserPage(page, limit, user);
        return userPage;
    }
    // 新增修改
    @PostMapping("/insertOrUpdateUser")
    @ApiOperation(value = "用户新增修改")
    public  R insertOrUpdateUser(@RequestBody User user){
        return userService.insertOrUpdateUser(user);
    }
    // 新增判断账号是否存在
    @PostMapping("/oneAccount")
    @ApiOperation(value = "新增判断账号是否存在")
    public R oneAccount(@RequestBody User user){
        String account= user.getAccount();
        if (!StringUtils.isNotEmpty(account)){
            return  R.error().message("请输入账号");
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",user.getAccount());
        List<User> list = userService.list(queryWrapper);
        if (list.size()>0){
            return  R.ok().message("该账号已重复");
        }else {
            return R.ok().message("该账号可以使用");
        }
    }
    // 根据Id删除
    @DeleteMapping("/deleteUser/{userId}")
    @ApiOperation(value = "用户删除")
    public R deleteUser(@PathVariable Long userId){
        boolean b = userService.removeById(userId);
        if (b){
            return R.ok().message("删除成功");
        }
        return R.ok().message("删除失败");
    }
    // 修改状态
    @PostMapping("/updateStatus/{userId}/{status}")
    @ApiOperation(value = "用户改变状态")
    public R updateUserStatus(@PathVariable(value = "userId") Long userId,@PathVariable(value = "status")  String status){
        return userService.updateStatus(userId,status);
    }
    // 部门树
    @GetMapping("/DeptTree")
    @ApiOperation(value = "用户部门树")
    public R DeptTree(){
        List<Integer> list=new ArrayList<>();
        list.add(25);
        R data = R.ok().data("deptTree", deptService.selectDeptTree()).data("extendNode", list);
        return data;
    }
    @GetMapping("/RoleTree/{userId}")
    @ApiOperation(value = "用户角色树")
    public R RoleTree(@PathVariable Long userId){
        List<Long> list = userService.selectRoleByUserId(userId);
        R data = R.ok().data("roleTree", roleService.selectRoleTree()).data("roles",list);
        return data;
    }
    @PostMapping("/updateRoleByUserId/{userId}")
    @ApiOperation(value = "用户分配角色" )
    public R updateRoleByUserId(@PathVariable Long userId,@RequestBody List<Long> roles){
        return userService.updateRoleByUserId(userId, roles);
    }
    @GetMapping("/findByUserId/{userId}")
    @ApiOperation(value = "修改时回显数据")
    public R findByUserId(@PathVariable Long userId){
        return userService.findByUserId(userId);
    }

    @PostMapping("/resetPwd")
    @ApiOperation(value = "重置密码")
    public R resetPwd(@RequestBody User user){
       return userService.resetPwd(user);
    }
}